package com.zyx.javademo.juc.basic;

import org.apache.commons.lang3.RandomUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author Yaxi.Zhang
 * @since 2021/8/11 17:57
 * desc: 多线程基本案例
 */
public class ThreadDemo {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            new MyThread("one thread " + i).start();
        }

        for (int i = 0; i < 3; i++) {
            // Thread implements Runnable
            // Thread构造方法中传入Runnable接口, 也可以传入lambda表达式
            Thread thread = new Thread(() -> {
                for (int j = 0; j < 20; j++) {
                    System.out.println(Thread.currentThread().getName() + " ===> " + j);
                    try {
                        TimeUnit.MILLISECONDS.sleep(RandomUtils.nextLong(1000L, 1500L));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.setName("another thread " + i);
            thread.start();
        }
    }

    static class MyThread extends Thread {

        public MyThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                System.out.println(Thread.currentThread().getName() + " ===> " + i);
                try {
                    TimeUnit.MILLISECONDS.sleep(RandomUtils.nextLong(1000L, 1500L));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
